package Demo1;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class addServlet extends HttpServlet {
//   注意:这里重写的是dopost方法
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        // 获取前端提交的数据
        String Deptno = req.getParameter("deptno");
        String Dname = req.getParameter("dname");
        String Loc = req.getParameter("loc");

        // 向数据库中插入数据
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        // 将deptno化作整数插入数据库
         int dno = Integer.parseInt(Deptno);
         int count = 0;
        String sql = "insert into dept(deptno,dname,loc) values(?,?,?)";
        try {
            connection = DBUtil.getConnection();
            preparedStatement = connection.prepareStatement(sql);
            // 设置值
            preparedStatement.setInt(1,dno);
            preparedStatement.setString(2,Dname);
            preparedStatement.setString(3,Loc);

            // 这里的返回值的值是受影响的行数
            count = preparedStatement.executeUpdate();
            System.out.println(count);

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.close(connection,preparedStatement,null);
        }
        if(count==1){
            // 成功,跳转到list界面,这里的跳转是不需要写项目名的,默认的根就是项目名
            // 注意这里的转发也是一次请求,这里的代码是post请求,但是list类中是get请求,为了避免报错,在list类中的post方法中调用get方法
            // 重定向可以从根本解决问题.
            req.getRequestDispatcher("/dept/list").forward(req,resp);
        }else {
            //失败
            req.getRequestDispatcher("/Adderror.html").forward(req,resp);
        }
    }
}
